package leetcode.top100;

import leetcode.util.CommonUtils;
import org.junit.Test;

import java.util.Arrays;

/**
 * @author ：zsy
 * @date ：Created 2022/10/20 11:29 PM
 * @description：https://leetcode.cn/problems/median-of-two-sorted-arrays/
 */
public class _004_寻找两个正序数组的中位数 {
    @Test
    public void test() {
        System.out.println(new Solution().findMedianSortedArrays(
                CommonUtils.genSortedIntArray(4, 10), CommonUtils.genSortedIntArray(3, 10)));
    }

    class Solution {
        public double findMedianSortedArrays(int[] nums1, int[] nums2) {
            int len1 = nums1.length;
            int len2 = nums2.length;
            int midIdx = len1 + len2 >> 1;
            int i = 0;
            int j = 0;
            int prev = 0;
            int midVal = 0;
            while (midIdx-- >= 0) {
                prev = midVal;
                midVal = (i < len1 ? nums1[i] : Integer.MAX_VALUE) < (j < len2 ? nums2[j] : Integer.MAX_VALUE) ? nums1[i++] : nums2[j++];
            }
            return (len1 + len2) % 2 == 0 ? (prev + midVal) / 2.0 : midVal;
        }
    }
}
